const express = require('express')
const User = require('../models/user')
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");


const router = express.Router();

router.post("/signup", (req, res, next) => {
  bcrypt.hash(req.body.password, 10).then(hash => {
    const user = new User({
      email: req.body.email,
      password: hash
    });

    User.findOne({ email: req.body.email }).then(user1 => {
      if (user1) {
        return res.status(401).json({
          message: "此用户已有"
        })
      }

      user.save().then(result => {
        if (!result) {
          return res.status(500).json({
            message: "创建用户错误"
          })
        }
        res.status(201).json({
          message: "创建用成功!",
          result: result
        });
      })
    })
      .catch(err => {
        res.status(500).json({
          error: err
        });
      });;
  })

});


router.post("/login", (req, res, next) => {
  let fetchedUser;

  User.findOne({ email: req.body.email }).then(user => {
    if (!user) {
      return res.status(401).json({
        message: "验证失败，无此用户"
      })
    }
    fetchedUser = user;
    return bcrypt.compare(req.body.password, user.password);
  }).then(result => {
    console.log(fetchedUser)
    if (!result) {
      return res.status(401).json({
        message: "验证失败，密码错误"
      })
    }
    const token = jwt.sign(
      { email: fetchedUser.email, userId: fetchedUser._id },
      "secret_this_should_be_longer",
      { expiresIn: "1h" }
    );
    res.status(200).json({
      token: token,
      expiresIn: 3600,
      userId: fetchedUser._id
    });
  })
    .catch(e => {

      console.log(e)

    })
})
module.exports = router